import { getLessons, getSlideList } from '@/api/home'
import { CATEGORY_TYPES, IHomeState, ILessons, ISlider, Response } from '@/typings/home'
import { Module } from "vuex"
import { IGlobalState } from '..'
import * as Types from '../action-types'
const state: IHomeState = {
    CurrentCategory: CATEGORY_TYPES.ALL,
    slides: [],
    lessons: {
        hasMore: true,
        loading: false,
        offset: 0,
        limit: 5,
        list: []
    }
}
// Module 参数一:自己的状态，参数二:全局的状态
const home: Module<IHomeState, IGlobalState> = {
    namespaced: true,
    state,
    mutations: {
        [Types.SET_CATEGORY](state, payload: CATEGORY_TYPES) {
            state.CurrentCategory = payload
        },
        [Types.SET_SLIDER_LIST](state, payload: ISlider[]) {
            state.slides = payload
        },
        [Types.SET_LOADING](state, payload: boolean) {
            state.lessons.loading = payload
        },
        [Types.SET_LESSON_LIST](state, payload: ILessons) {
            state.lessons.list = [...state.lessons.list,...payload.list]
            state.lessons.hasMore = payload.hasMore
            state.lessons.offset = state.lessons.offset+payload.list.length
        }
    },
    actions: {
        async [Types.SET_SLIDER_LIST]({ commit }) {
            let slides = await getSlideList<Response<ISlider>>()
            console.log(slides.data)
            let data = slides.data
            commit(Types.SET_SLIDER_LIST, data)
        },
        async [Types.SET_LESSON_LIST]({ commit }) {
            if (state.lessons.loading) {
                return
            }
            if (!state.lessons.hasMore) {
                return
            }
            commit(Types.SET_LOADING, true)//开始加载
            let lessons = await getLessons<Response<ILessons>>(state.CurrentCategory, state.lessons.offset, state.lessons.limit)
            commit(Types.SET_LESSON_LIST, lessons.data)
            commit(Types.SET_LOADING, false)
        }
    }
}

export default home